package com.highstockings.utils;




import com.google.gson.Gson;
import com.highstockings.model.QiniuInfo;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by diablo13064 on 2018/3/26.
 */
@Component
public class QiniuUtil {
    /*org.junit.platform.commons.logging.Logger logger = org.junit.platform.commons.logging.LoggerFactory.getLogger(QiniuUtil.class);*/
    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.domain}")
    private String domain;
    @Value("${qiniu.bucket}")
    private String bucket;


    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getBucket() {
        return bucket;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    public Map<String,String> uploadPicture() {
        Map<String, String> map = new HashMap<>();



        return map;
    }
    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken(){
        //密钥配置
        Auth auth = Auth.create(getAccessKey(), getSecretKey());

        //基本的定义回调对象(returnBody好使)
        long expireSeconds = 3600;
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        return auth.uploadToken(getBucket(), null, expireSeconds, putPolicy);
    }
    public QiniuInfo upload(byte[] file, String key) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone1());
        //...其他参数参考类注释
        //创建上传对象
        UploadManager uploadManager = new UploadManager(cfg);
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        try {
            //调用put方法上传
            Response res = uploadManager.put(file, key, getUpToken());
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            //打印返回的信
            return new Gson().fromJson(res.bodyString(), QiniuInfo.class);
            //return res.bodyString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        return null;
    }


    /**
     *
     * @param fileName
     * @return
     * @throws UnsupportedEncodingException
     */
    public String getPublicDownLink(String fileName) throws UnsupportedEncodingException {
        /*String fileName = "七牛/云存储/qiniu.jpg";
        String domainOfBucket = "http://devtools.qiniu.com";*/
        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String finalUrl = String.format("%s/%s", getBucket(), encodedFileName);
        return getDomain()+finalUrl.replace(getBucket(),"");

    }

    /**
     *
     * @param fileName
     * @return
     * @throws UnsupportedEncodingException
     */
    public String getSecretDownLink(String fileName) throws UnsupportedEncodingException {
        //String fileName = "七牛/云存储/qiniu.jpg";
        //String domainOfBucket = "http://devtools.qiniu.com";
        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String publicUrl = String.format("%s/%s", getBucket(), encodedFileName);
        //String accessKey = "your access key";
        //String secretKey = "your secret key";
        Auth auth = Auth.create(getAccessKey(), getSecretKey());
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        //System.out.println(finalUrl);

        return getDomain()+finalUrl.replace(getBucket(),"");
    }

    /**
     * 获取文件名的时间戳
     * @param file
     * @return
     */
    public LinkedHashMap<String,String> getFileMapBy(File file) throws FileNotFoundException {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        if (file.isDirectory() && file.exists()) {
            File[] files = file.listFiles();
            for (File f : files) {
                if (f.getName().endsWith(".jpg")) {
                    //map.put(f.getName(),)
                }
            }
        }
        return map;
    }

}
